const { series, src, dest,task } = require('gulp')

var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var template = require('gulp-template');
var clean = require('gulp-clean');
var fs = require('fs');
var path = require('path');

//----------------  配置信息 -------------------
var fontName = 'duIcon';
var cssName = 'duIcon'
//----------------  配置信息 -------------------

/**
 * 任务：svg转字体
 * @returns 
 */
function compile(){
  return src(['assets/icons/*.svg'])
    .pipe(iconfontCss({
      fontName: fontName,
      path: 'assets/templates/_icons.css',            // 模板路径
      targetPath: '../icons.css',                    // CSS 文件保存的路径，相对于中使用的路径
      fontPath: './fonts/',
      cssClass: cssName                               // 生成的 CSS 类/占位符的名称
    }))
    .pipe(iconfont({
      fontName: fontName,
      prependUnicode: true,
      formats: ['ttf', 'eot', 'woff','woff2'],
      timestamp: Math.round(Date.now()/1000),
      // normalize: true
    }))
    .on('glyphs', function(glyphs, options) {
      // CSS templating, e.g.
      console.log(glyphs, options);
    })
      .pipe(dest('dist/fonts/'))
}
/**
 * 任务：替换base64字体
 * @returns 
 */
function base64Replace(){
  return src(['dist/fonts/*.woff2'])
      .on('end', function() {
        // Read the woff2 file
        const fontPath = path.resolve('dist/fonts/', `${fontName}.woff2`);
        const fontData = fs.readFileSync(fontPath);
        // Convert to base64
        const base64Font = fontData.toString('base64');
        
        // Insert into CSS
        const cssPath = path.resolve('dist/', 'icons.css');
        let cssContent = fs.readFileSync(cssPath, 'utf8');
        
        cssContent = cssContent.replace(/url\(.*\) format\('woff2'\)/, `url('data:application/font-woff2;charset=utf-8;base64,${base64Font}') format('woff2')`);
        fs.writeFileSync(cssPath, cssContent, 'utf8');
      });
}
/**
 * 任务：清空dist目录
 * @returns 
 */
function cleanTask(){
  return src('dist/',{read: false}).pipe(clean());
}

/**
 * 任务：生成demo页面
 * @returns 
 */
function demo (){
  icons = fs.readdirSync('assets/icons').map((icon)=> {
    return icon.replace(/\.\w+$/, '');
  });
  return src(`assets/templates/index.html`) //样式例子文件
  .pipe(template({ icons: icons, cssName: cssName,fontName:fontName }))
      .pipe(dest("dist/"));
};

// 增加base64Replace 会替换woff2 为 base64
exports.build = series(cleanTask,compile,base64Replace,demo)

exports.demo = series(demo)